package com.liuhangs.learning.crowd.webui.security.provider;

import com.liuhangs.learning.crowd.util.RsaUtil;
import com.liuhangs.learning.crowd.webui.mapper.AdminUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

@Component
public class AdminAuthenticationProvider implements AuthenticationProvider {

    @Autowired
    @Qualifier("userSecurityServiceImpl")
    private UserDetailsService userDetailsService;

    @Autowired
    private AdminUserMapper adminUserMapper;

    /** RSA2私钥 */
    @Value("${auth.privateKey}")
    private String RSA_PRIVATE_KEY;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException
    {
        // 获取前端表单中输入后返回的用户名、密码
        String userName = (String) authentication.getPrincipal();
        String password = (String) authentication.getCredentials();

        UserDetails userInfo = userDetailsService.loadUserByUsername(userName);
        if(null == userInfo || StringUtils.isEmpty(userInfo.getUsername())) {
            throw new UsernameNotFoundException("用户不存在！");
        }

        //解密前端用户输入的密码（RSA2加密）
        String decodePasswprd = RsaUtil.decrypt(password, RSA_PRIVATE_KEY);
        boolean isValid = new BCryptPasswordEncoder().matches(decodePasswprd, userInfo.getPassword());
        //boolean isValid = PasswordUtils.isValidPassword(password, userInfo.getPassword(),
            //userInfo.getCurrentUserInfo().getSalt());
        // 验证密码
        if (!isValid) {
            throw new BadCredentialsException("密码错误！");
        }

        // 前后端分离情况下 处理逻辑...
        // 更新登录令牌 - 之后访问系统其它接口直接通过token认证用户权限...
//        String token = PasswordUtils.encodePassword(System.currentTimeMillis() + userInfo.getCurrentUserInfo().getSalt(), userInfo.getCurrentUserInfo().getSalt());
//        User user = adminUserMapper.selectById(userInfo.getCurrentUserInfo().getId());
//        user.setToken(token);
//        userMapper.updateById(user);
//        userInfo.getCurrentUserInfo().setToken(token);
        return new UsernamePasswordAuthenticationToken(userInfo, password, userInfo.getAuthorities());
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return true;
    }
}